﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using LS.Infrastructure.UtilsExtension;
using QInfrastructure.Models.SystemManager;
using QInfrastructure.Models;

namespace QInfrastructure.WebCore.Filters;


public class PermissionFilter : ActionFilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //1. 获取区域、控制器、Action的名称
        //必须在区域里的控制器上加个特性[Area("")]才能获取
        var areaName = context.ActionDescriptor.RouteValues["area"] == null ? "" : context.ActionDescriptor.RouteValues["area"].ToString();
        var controllerName = context.ActionDescriptor.RouteValues["controller"] == null ? "" : context.ActionDescriptor.RouteValues["controller"].ToString();
        var actionName = context.ActionDescriptor.RouteValues["action"] == null ? "" : context.ActionDescriptor.RouteValues["action"].ToString();
        
         



    }

	public override void OnActionExecuting(ActionExecutingContext context)
	{
		if (context.Controller is Controller temp)
        {
			if (temp != null)
            {
				if (temp is QBaseController qtemp)
                {
					if (qtemp != null)
					{
						var userId = context.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
						if (userId != null && userId.Value.IsNot_NullOrWhiteSpace())
						{
							var LoginUserId = Guid.Parse(userId.Value);
							var users = QInfrastructureCache.GetQCache<SystemUser>();
							if (users.Count > 0)
							{
								var tmpuser = users.FirstOrDefault(x => x.Id == LoginUserId);
								if (tmpuser != null)
								{
									tmpuser.UserPwd = "";
									qtemp.CurrentUser = tmpuser;
									
								}
							}
							var themes = QInfrastructureCache.GetQCache<SystemUserTheme>();
							SystemUserTheme currentTheme=null;
							if (themes.Count > 0)
							{
								currentTheme=themes.FirstOrDefault(x=>x.UserId==LoginUserId);
							}

							if(currentTheme==null)
							{
								currentTheme=new SystemUserTheme { ThemeName = "default" };
							}
							temp.ViewData.Add("CurrentTheme", currentTheme);

						}
					}
				}

			}

		}
		base.OnActionExecuting(context);
	}

	public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Controller is Controller temp)
        {
            if (temp != null)
            {
                temp.ViewData.Add("Permission", 15);

				
            }
            
        }
    }



}